package main

import (
	"fmt"
	"sync"
)

func main() {
	definitionDemo()
	//bufferedChannel()
}

type Worker struct {
	in   chan int
	done chan bool
}

var wg sync.WaitGroup

func definitionDemo() {
	var workers [10]Worker //nil
	for i := 0; i < 10; i++ {
		workers[i] = createWorker(i)
	}
	//使用waitGroup
	wg.Add(20)
	for i := 0; i < 10; i++ {
		workers[i].in <- 'a' + i
	}
	for i := 0; i < 10; i++ {
		workers[i].in <- 'A' + i
	}
	//wait for all
	//for _, worker := range workers {
	//	<-worker.done
	//	<-worker.done
	//}
	wg.Wait()
}

func doWork(id int, c chan int, done chan bool) {
	for n := range c {
		fmt.Printf("Worker %d received %c \n", id, n)
		wg.Done()
		//go func() {
		//	done <- true
		//}()
	}
	//for {
	//	if n, ok := <-w.in; ok {
	//		fmt.Printf("Worker %d received %c \n", id, n)
	//	} else {
	//		w.done <- true
	//		break
	//	}
	//}
}

// 返回channel的常见写法
func createWorker(id int) Worker {
	w := Worker{
		in:   make(chan int),
		done: make(chan bool),
	}
	go doWork(id, w.in, w.done)
	return w
}

func bufferedChannel() {
	//c := make(chan int, 3)
	//go work(0, c)
	//c <- 'a'
	//c <- 'b'
	//c <- 'c'
	//close(c)
	//time.Sleep(time.Millisecond)
}
